<template>
  <view>
    <van-cell is-link @click="returnTerminal" custom-class="changeTerminal">
      <template #title>
        {{selectData.equName}}
        <span v-for="status in statusList" :key="status.label" class="tag"
          :style="{'color': status.textColor,'backgroundColor': status.color, 'display': status.value === selectData.onlintStatus ? 'inline-block': 'none'}">
          {{status.label}}
        </span>
      </template>
    </van-cell>
    <!-- 终端详情 -->
    <view class="card">
      <view class="title">
        <span class="headerIcon"></span>
        {{ selectData.equTypeName }}
        <!-- <image src="/static/manage/out.png" class="terminalType"></image> -->
        <image :src="`/static/manage/${selectData.impExp === 1 ? 'in' : 'out'}.png`" class="terminalType"></image>

        <!-- <span class="tag-status">运行</span> -->

      </view>
      <view style="margin-top: 20rpx">
        <!-- <view class="monitorTitle">
          <span class="titleIcon"></span>
          监测数据
        </view> -->
        <view class="monitorItem">
          <view class="label">设备编号</view>
          <view class="value">{{selectData.equNo}}</view>
        </view>
        <view class="monitorItem">
          <view class="label">关联{{villageType == 1 ? '接驳井':'终端'}}</view>
          <view class="value">{{ selectData.terminalName }}</view>
        </view>
        <view class="chartOperate">
          <view class="dateTypeBox">
            <span>日期</span>
            <view @click="openDateSelect=true" class="dateTypePicker">
              <span class="selectValue">{{ queryParams.startDate }}</span>
              <van-icon name="arrow-down" class="selectIcon" />
            </view>
            <span class="saperator">—</span>
            <view @click="openDateSelect=true" class="dateTypePicker">
              <span class="selectValue">{{ queryParams.endDate }}</span>
              <van-icon name="arrow-down" class="selectIcon" />
            </view>

            <!-- <van-calendar v-if="openDateSelect" :show="openDateSelect" @close="onClose" @confirm="onConfirm" /> -->
            <!-- <van-action-sheet :actions="dateTypeList" v-if="openDateSelect" :show="openDateSelect" title="请选择"
              @select="onSelect" @close="onClose">
            </van-action-sheet> -->
          </view>
          <view class="newValue">当前数值 <span :class="(thersholdArr[1] &&( rtd < thersholdArr[1] && rtd > thersholdArr[0])) || 
          (thersholdArr[0] && !thersholdArr[1]) && rtd < thersholdArr[0] ? 'green': 'red'"
              class="newValueNum">{{rtd}}</span></view>
          <van-calendar :show="openDateSelect" ref="calendar" :defaultDate="defaultDate" :maxDate="maxDate"
            :minDate="minDate" monthNum="24" rowHeight="55" title="选择时间" type="range" @confirm="dateConfirm"
            color="rgba(39, 105, 247, 1)" @close="dateClose">
          </van-calendar>
        </view>
        <!-- 图表 :force-use-old-canvas="true" -->
        <uni-ec-canvas-vue class="uni-ec-canvas" id="uni-ec-canvas" ref="canvas" canvas-id="uni-ec-canvas"
          :ec="ech"></uni-ec-canvas-vue>

      </view>
    </view>
  </view>
</template>

<script>
import { geEquDetailEquData } from '@/api/manage'
import uniEcCanvasVue from './common/uni-ec-canvas/uni-ec-canvas.vue'
import * as echarts from './common/uni-ec-canvas/echarts'
let chart = null

export default {
  components: {
    uniEcCanvasVue
  },
  props: {
    selectData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /**村庄类型：
    *  1-纳场村
    *  2-终端村
    */
    villageType: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      defaultDate: [],
      maxDate: new Date().valueOf(),
      minDate: new Date('2024-01-01').getTime(),
      rtd: null,
      thersholdArr: [],
      formData: {
        today: 12,
        yestoday: 12,
        month: 12,
        lastMonth: 12,
      },
      energyList: [
        { label: '今日耗能', prop: 'today' },
        { label: '昨日耗能', prop: 'yestoday' },
        { label: '本月耗能', prop: 'month' },
        { label: '上月耗能', prop: 'lastMonth' },
      ],
      openDateSelect: false,
      dateTypeList: [{ name: '当天' }, { name: '7天' }, { name: '30天' }],
      dateType: '7天',
      activeValue: '液位',
      ech: {
        lazyLoad: true
      },
      statusList: [
        { label: '未激活', value: 1, color: '#FFFFE5', textColor: '#FBD94C' },
        { label: '在线', value: 2, color: '#D5EFE7', textColor: '#74CDAF' },
        { label: '离线', value: 3, color: '#E1E1E1', textColor: '#8E8E8E' }
      ],
      option: {
        legend: {
          show: true,
          icon: 'circle',
          itemWidth: 6,
          itemHeight: 6,
          top: 0,
        },
        tooltip: {
          trigger: 'axis',
          // formatter: function (params, tikect) {
          //   console.log(params, tikect, '图表tooltip')
          // },
          // formatter: (params, tikect) => {
          //   let str = params[0].name + '\n'
          //   //params是数组格式
          //   for (let item of params) {
          //   //设置浮层图形的样式跟随图中展示的颜色
          //     str += this.queryParams.equType + "数值\t" + item.value 
          //     // str +=  "液位高度\t" + item.value + 'cm'
          //     // str +=  "<span style='display:inline-block;width:10px;height:10px;border-radius:10px;background-color:" + item.color + ";'></span>" + "\t" + "液位高度\t" + item.value
          //   }
          //   return str
          //   // return params[0].axisValue + "<span style='display:inline-block;width:6px;height:6px;background-color:#3576F2;border-radius: 50px;margin:10px'></span>\n液位高度：" + params[0].value + 'cm'
          // }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '28%'
        },
        xAxis: {
          type: 'time',
          name: '日期',
          nameLocation: 'end',
          nameGap: 3,
          // boundaryGap: false,
          boundaryGap: ['23%', '23%'],
          // 注： x轴不指定data,自动会从series取
          axisLine: {
            lineStyle: {
              color: 'rgba(24,24,24,0.25)'
            }
          },
          axisTick: {
            lineStyle: {
              color: 'rgba(24,24,24,0.25)'
            }
          },
          axisLabel: {
            // interval: 'auto', // 显示所有标签
            splitNumber: 6,
            formatter: this.formatter

          },
          // data: []
        },
        yAxis: {
          name: '',
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            textStyle: {
              color: '#a3a3a3'
            }
          },
          nameTextStyle: {
            color: '#a3a3a3'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(24,24,24,0.1)', // 网格线颜色
              // type: 'dashed' // 线的类型，可以是 'solid', 'dashed', 或 'dotted'
            }
          }
        },
        dataZoom: [
          {},
          {
            type: 'inside'
          }
        ],
        series: [
          // 进出水口动态判断
          {
            name: this.selectData.impExp === 1 ? '进水口' : '出水口',
            type: 'line',
            color: this.selectData.impExp === 1 ? '#3C8AFF' : '#FAE021',
            data: [],
          }
        ]
      },
      startDate: '',
      endDate: '',
      queryParams: {
        startDate: '',
        endDate: '',
        equNo: ''
      }
    }
  },
  watch: {
    selectData: {
      handler: function (val) {
        if (val.equNo) {
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        // this.queryParams.startDate = 
        this.getDefaultDateRange()
        console.log(this.$refs.canvas, 'this.$refs.canvas')
        if (this.$refs.canvas) {
          this.$refs.canvas.init(this.initChart)
          this.geEquDetailEquData()
        }
      }, 500)
    })

  },
  methods: {
    unitText(equipType) {
      // ['cm 液位高度','m3/h 流量','mg/L 氨氮含量','PH值 PH值','mg/L COD','us/cm 电导率','cm 液位高度']
      const unitObj = {
        1: "液位高度 cm",
        2: "流量 m3/h",
        3: "氨氮含量 mg/L",
        4: "PH值 ph",
        5: "COD mg/L",
        6: "电导率 us/cm",
        7: "液位高度 cm",
        8: "电流 A",
        // 9: "浊度 mg/L",
      };
      return unitObj[Number(equipType)];
    },
    getDefaultDateRange() {
      const endDate = new Date(new Date()).format('yyyy-MM-dd')
      const startDate = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000)).format('yyyy-MM-dd')
      console.log(startDate, endDate, '初始化时间')
      this.queryParams = {
        ...this.queryParams,
        startDate, endDate
      }
      this.defaultDate = [startDate, endDate]
    },
    formatter(value) {
      const dates = (new Date(this.queryParams.endDate) - new Date(this.queryParams.startDate)) / (1000 * 60 * 60 * 24)
      // console.log(value, dates, '图表x轴刻度')
      let xAxisLabel = "";
      if (dates <= 1) {
        xAxisLabel = new Date(value).format("hh:mm");
      } else if (dates > 1 && dates < 7) {
        xAxisLabel = new Date(value).format("MM-dd");
      } else if (dates >= 7) {
        xAxisLabel = new Date(value).format("dd");
      }
      return xAxisLabel;
    },
    geEquDetailEquData() {
      this.queryParams.equNo = this.selectData.equNo
      geEquDetailEquData(this.queryParams).then(({ data }) => {
        const thersholdArr = data.data?.operatorType && [1, 2, 4].includes(data.data.operatorType) ? [data.data?.threshold, null] :
          data.data?.operatorType === 3 ? [data.data?.threshold, data.data?.maxThre] : []

        // const minvalue = thersholdArr[0] > thersholdArr[1] ? thersholdArr[1] : thersholdArr[0]
        // const maxvalue = thersholdArr[0] > thersholdArr[1] ? thersholdArr[0] : thersholdArr[1]
        this.thersholdArr = thersholdArr
        this.rtd = data.data.rtd
        const name = this.unitText(data.data.equType)
        const markLineData = []
        thersholdArr.forEach((val, i) => {
          if (val || val === 0) {
            markLineData.push(
              {
                name: `警戒线`,
                yAxis: val,
                lineStyle: {
                  type: 'dashed',
                  color: 'transparent',
                  dashOffset: 5
                },
                label: {
                  show: true,
                  position: 'end',
                  color: 'red',
                  fontWeight: 'bold',
                  distance: 0,
                  formatter: () => {
                    return '警戒线'
                  }
                },
              },
              {
                name: `警戒线`,
                yAxis: val,
                lineStyle: {
                  type: 'dashed',
                  color: '#FF0000',
                  dashOffset: 5
                },
                label: {
                  show: true,
                  position: 'start',
                  color: 'red',
                  fontWeight: 'bold',
                  distance: 0,
                  formatter: (params) => {
                    return params.value
                  }
                },
              }
            )
          }
        })
        console.log(data, thersholdArr, 'data--获取设备详情')
        const dataList = data.data.rtdList
        let dates = (new Date(this.queryParams.endTime) - new Date(this.queryParams.startTime)) / (24 * 60 * 60 * 1000)

        if (dataList && dataList.length) {
          // this.option.xAxis.data = dataList.map(function (item) {
          //   let date = item.reportTime.split(' ')[0]
          //   let time = item.reportTime.split(' ')[1]
          //   return dates >= 0 && dates <= 7 ? time.slice(0, 5) :
          //     dates > 7 && dates <= 30 ? date.slice(5) :
          //       dates > 30 ? (date.slice(8) === '01' ? date.slice(5) : date.slice(8)) : date.slice(5)
          // })
          this.option.series[0].data = dataList.map(function (item) {
            return [item.reportTime, Number(item.rtd)];
          })
          const valueList = data.data.rtdList.map(item => item.rtd)
          const maxvalue = Math.max(...valueList)
          const minvalue = Math.min(...valueList)
          if (data.data?.operatorType === 3) {
            const min = data.data?.threshold > minvalue ? minvalue : data.data?.threshold
            const max = data.data?.maxThre > maxvalue ? data.data?.threshold : maxvalue
            this.option.yAxis.min = min >= 0 ? 0 : min
            if (max) this.option.yAxis.max = max

          } else {
            const max = data.data?.threshold > maxvalue ? data.data?.threshold : maxvalue
            this.option.yAxis.interval = max < 1 ? 0.1 :
              max > 1 && max <= 10 ? 2 :
                max > 10 && max <= 20 ? 5 :
                  max > 10 && max <= 50 ? 10 :
                    max > 50 && max <= 100 ? 20 :
                      max > 100 && max <= 350 ? 50 :
                        max > 350 && max <= 700 ? 100 :
                          max > 700 ? 200 : 1
            if (max) this.option.yAxis.max = max < 1 ? max.toFixed(1) : Math.ceil(max / this.option.yAxis.interval) * this.option.yAxis.interval
            // maxInterval,
          }
          this.option.series[0].markLine = {
            symbol: 'none',
            data: markLineData,
            lineStyle: {
              width: 2
            }
          }
          console.log(this.option, minvalue, maxvalue, '获取option')

        } else {
          // this.option.xAxis.data = []
          this.option.series[0].data = []
        }
        this.option.yAxis.name = name
        console.log(name, 'name------')
        chart.setOption(this.option)

      })
    },
    dateConfirm(e) {
      const [startDate, ...dateList] = e.detail
      this.queryParams = {
        ...this.queryParams,
        startDate: new Date(startDate).format('yyyy-MM-dd'),
        endDate: e.detail.length ? new Date(e.detail[e.detail.length - 1]).format('yyyy-MM-dd') : ''
      }
      console.log(e, this.queryParams, '时间选择')
      this.openDateSelect = false
      this.geEquDetailEquData()
    },
    dateClose() {
      this.openDateSelect = false
    },
    toBaseInfo() {
      this.$tab.navigateTo('/subpack_Manage_VillageDetail/villageDetail/baseInfo')
    },
    returnTerminal() {
      console.log('触发')
      uni.$emit('returnTerminal', { selected: false })
    },
    initChart(canvas, width, height, canvasDpr) {
      console.log('初始化图表', chart)
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: canvasDpr
      })
      canvas.setChart(chart)
      chart.setOption(this.option)
      return chart
    },
  }
}
</script>

<style lang="scss" scoped>
.uni-ec-canvas {
  width: calc(100% + 56rpx);
  height: 600rpx;
  margin-left: -28rpx;
  display: block;
}
.energyLsit {
  display: flex;
  justify-content: space-between;
  margin-bottom: 48rpx;
  .energyItem {
    text-align: left;
    font-weight: bold;
    font-size: 28rpx;
    color: #4a4a4a;
    line-height: 40rpx;
    .energyValue {
      font-weight: 800;
      font-size: 32rpx;
      color: #3c8aff;
      line-height: 44rpx;
      .indexIcon {
        width: 22rpx;
        height: 27rpx;
        margin-left: 24rpx;
      }
    }
  }
}
.monitorTitle {
  font-weight: 800;
  font-size: 28rpx;
  color: #4a4a4a;
  line-height: 40rpx;
  margin: 32rpx 0;
  .titleIcon {
    display: inline-block;
    width: 8rpx;
    height: 20rpx;
    background: #2769f7;
    border-radius: 6rpx;
    opacity: 0.6;
    margin: 0 16rpx;
  }
}
.chartOperate {
  // display: flex;
  // justify-content: space-between;
  .dateTypeBox {
    display: flex;
    justify-content: space-around;
    font-weight: bold;
    font-size: 28rpx;
    color: #5e5e5e;
    line-height: 40rpx;
    margin: 36rpx 0;
    align-items: center;
    width: 100%;
    .saperator {
      color: #ebebeb;
    }
    .dateTypePicker {
      width: 180rpx;
      height: 56rpx;
      background: #f2f6f7;
      border-radius: 32rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #4a4a4a;
      line-height: 34rpx;
      padding-right: 22rpx;
      margin-left: 16rpx;
      position: relative;
      .selectIcon {
        position: absolute;
        right: 22rpx;
        top: 20rpx;
      }
    }
    .selectValue {
      line-height: 56rpx;
      margin-left: 20rpx;
    }
  }
}
.deviceTab {
  margin: 36rpx 0;
  .defalutTab {
    display: inline-block;
    border-radius: 6rpx;
    border: 1rpx solid #2769f7;
    // opacity: 0.5;
    font-weight: bold;
    font-size: 24rpx;
    color: #3c8aff;
    line-height: 34rpx;
    padding: 4rpx 12rpx;
    margin-left: 12rpx;
  }
  .selectedTab {
    background: #2769f7;
    color: #ffffff !important;
  }
}
.monitorItem {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  margin-left: 16rpx;
  .label {
    font-weight: bold;
    font-size: 28rpx;
    color: #989898;
    line-height: 40rpx;
  }
  .value {
    font-weight: bold;
    font-size: 28rpx;
    color: #5e5e5e;
    line-height: 40rpx;
  }
  .monitorAddress {
    font-weight: 800;
    font-size: 28rpx;
    color: #4a4a4a;
    line-height: 40rpx;
    .monitorTypeIcon {
      width: 24rpx;
      height: 24rpx;
      margin-left: 16rpx;
    }
  }
}
::v-deep .changeTerminal {
  text-align: left;
  border-radius: 10rpx;
  .tag {
    // position: absolute;
    // right: 0;
    // top: 0;
    display: inline-block;
    padding: 2rpx 24rpx;
    border-radius: 6rpx;
    font-size: 24rpx;
    margin-right: 12rpx;
    margin-left: 12rpx;
  }
}
::v-deep .van-cell {
  border-radius: 6rpx;
}
.card {
  margin-top: 16rpx;
  background: #fff;
  padding: 24rpx 28rpx;
  border-radius: 6rpx;
  text-align: left;
  font-weight: 800;
  font-size: 32rpx;
  color: #4a4a4a;
  line-height: 44rpx;
  .title {
    position: relative;
    .headerIcon {
      display: inline-block;
      width: 8rpx;
      height: 20rpx;
      background: #2769f7;
      border-radius: 6rpx 6rpx 6rpx 6rpx;
      opacity: 0.6;
      margin-right: 12rpx;
    }
    .terminalType {
      width: 24rpx;
      height: 24rpx;
      margin-left: 12rpx;
    }
  }
  .newValue {
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 28rpx;
    color: #5e5e5e;
    .green {
      color: #74cdaf;
    }
    .red {
      color: #fc8382;
    }
    .newValueNum {
      font-size: 32rpx;
      margin-left: 24rpx;
    }
  }
}
</style>